package com.x.erp.manage;

import com.x.erp.dao.ContractRegionDao;
import com.x.erp.model.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.x.erp.model.Contract;
import com.x.erp.model.ContractRegion;
import com.x.framework.manage.BaseManage;


@Service
public class ContractRegionManage extends BaseManage {

	/**
	 * 新增合同区域信息
	 * @param car
	 * @return
	 * @throws Exception
	 */

	@Autowired
	private ContractRegionDao contractRegionDao;

	public ContractRegion insertContractRegion(ContractRegion contractRegion) throws Exception {
//		if(contractRegion.getContract() != null) {
//			Contract contract = contractRegion.getContract();
//			this.insert(contract);
//			contractRegion.setContractId(contract.getContractId());
//		}
		ContractRegion cr = this.insert(contractRegion);
		updateRegionRestNum(contractRegion);
		return cr;
	}

	public void updateContractRegion(ContractRegion contractRegion) throws Exception {
		this.update(contractRegion);
    	updateRegionRestNum(contractRegion);
	}

	public void deleteContractRegion(ContractRegion contractRegion) throws Exception {
		this.delete(contractRegion);
		updateRegionRestNum(contractRegion);
	}

	private  void  updateRegionRestNum(ContractRegion contractRegion) throws Exception{
		Integer contractRegionSum = contractRegionDao.selectContractRegionSum(contractRegion);
		Region region = contractRegion.getRegion();
		Integer restNum = region.getRegionNum() - contractRegionSum ;
		region.setRegionRestNum(restNum);
		this.update(region);
	}

}
